<template>
  <div class="health-container">
    <el-card>
      <h2>系统健康检查</h2>
      <div class="status-grid">
        <div class="status-item">
          <h3>后端服务</h3>
          <el-tag :type="backendStatus ? 'success' : 'danger'">
            {{ backendStatus ? '正常' : '异常' }}
          </el-tag>
          <div class="meta" v-if="backendStatusInfo">
            <div>版本：{{ backendStatusInfo.version || '-' }}</div>
            <div>时间：{{ backendStatusInfo.time || '-' }}</div>
          </div>
        </div>
        <div class="status-item">
          <h3>AI服务</h3>
          <el-tag :type="aiStatus ? 'success' : 'danger'">
            {{ aiStatus ? '正常' : '异常' }}
          </el-tag>
          <div class="meta" v-if="aiInfo">
            <div>向量库：{{ aiInfo.vector_db }}</div>
            <div>嵌入：{{ aiInfo.embeddings }}</div>
            <div v-if="aiLimits">限流：{{ aiLimits.rpm }}/min 并发：{{ aiLimits.maxConcurrency }}</div>
          </div>
        </div>
      </div>
      <el-button @click="checkHealth" :loading="loading">
        重新检查
      </el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { authApi } from '@/api/auth'
import axios from 'axios'

const backendStatus = ref(false)
const aiStatus = ref(false)
const loading = ref(false)
const backendStatusInfo = ref<any>(null)
const aiInfo = ref<any>(null)
const aiLimits = ref<{ rpm: number; maxConcurrency: number } | null>(null)

const checkHealth = async () => {
  loading.value = true
  
  try {
    // 检查后端健康状态
    const res = await authApi.health()
    backendStatus.value = true
    backendStatusInfo.value = { version: res?.version, time: new Date().toLocaleString() }
  } catch {
    backendStatus.value = false
    backendStatusInfo.value = null
  }
  
  try {
    // 检查AI服务健康状态
    const { data } = await axios.get('/ai/health')
    aiStatus.value = !!data?.ok
    aiInfo.value = data
    // 从环境或后端约定的头部/变量读取限流并发（此处用约定路径 /ai/health 即可不失败）
    aiLimits.value = {
      rpm: Number(import.meta.env.VITE_AI_ASK_RPM || 30),
      maxConcurrency: Number(import.meta.env.VITE_AI_MAX_CONCURRENCY || 4)
    }
  } catch {
    aiStatus.value = false
    aiInfo.value = null
    aiLimits.value = null
  }
  
  loading.value = false
}

onMounted(() => {
  checkHealth()
})
</script>

<style scoped>
.health-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.status-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin: 20px 0;
}

.status-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.status-item .meta {
  margin-top: 8px;
  color: #606266;
  font-size: 12px;
}

h2, h3 {
  margin: 0 0 10px 0;
}
</style>